<template>
  <Auth>
    <Card :padding="0">
      <div class="Audit-page">
        <Table :loading="loading" :columns="columns" :data="data">
          <template #name="{ row }">
            <Avatar icon="ios-person" :src="row.avatar" class="ivu-mr-8" />
            <strong>{{ row.name }}</strong>
          </template>
          <template #image="{ row }">
            <div class="audit-image-box" style="padding: 20px 0">
              <Image
                id="auditImage"
                @click.stop="toViewImage(row)"
                lazy
                :src="row.image"
                width="80px"
                height="80px"
              />
            </div>
          </template>
          <template #action="{ row }">
            <Button
              @click="toViewImage(row)"
              shape="circle"
              size="small"
              type="success"
              class="ivu-mr-8"
              >审查图片</Button
            >
            <Button
              shape="circle"
              size="small"
              type="error"
              @click="unpass(row)"
              >不通过</Button
            >
          </template>
        </Table>
        <div class="ivu-mt ivu-mb ivu-text-center">
          <Page
            :total="allAuditNum"
            show-total
            show-elevator
            @on-change="pageChange"
            @on-prev="pageChange"
            @on-next="pageChange"
          />
        </div>

        <Drawer
          :styles="drawstyles"
          width="33%"
          placement="left"
          @on-visible-change="ischange"
          :closable="false"
          v-model="imageViewModal"
          title="原图审核"
        >
          <div class="modal-image-box">
            <div @click="addPoint($event)" id="auditImg">
              <Image :src="imageViewSrc" style="width: 100%" />
            </div>
          </div>
          <Divider v-if="htmlUrl"></Divider>
          <div v-if="htmlUrl">
            <h4 class="ivu-text-center">预览序图</h4>
            <!-- <img :src="htmlUrl" /> -->
            <Image :src="htmlUrl" lazy />
            <canvas
              ref="headCanvas"
              style="position: absolute; height: 0; width: 0; opacity: 0"
            ></canvas>
          </div>
          <div class="drawer-footer">
            <ButtonGroup>
              <Button @click="cancel" type="primary" shape="circle"
                >清空序号
                <Icon type="ios-trash" size="15" />
              </Button>
              <Button type="primary" shape="circle" @click="view"
                >预览序图</Button
              >
            </ButtonGroup>
            <Button class="ivu-ml-8" type="success" shape="circle" @click="pass"
              >上传至服务器</Button
            >
          </div>
        </Drawer>
      </div>
    </Card>
    <template #noMatch>
      <Alert type="error">权限不足</Alert>
    </template>
  </Auth>
</template>

<script>
import { upload, get } from "@/utils/http";
import html2canvas from "html2canvas";
import { drag } from "../../components/pointer";
export default {
  name: "AuditView",
  data() {
    return {
      allAuditNum: 0,
      loading: false,
      currentPage: 1,
      imageViewModal: false,
      count: 0,
      drawstyles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static",
      },
      userAccess: "",
      imageViewSrc: "",
      //   点击序号后生成的图片
      htmlUrl: "",
      imageViewModalLayout: {
        width: "",
        height: "",
      },
      columns: [
        {
          title: "编号",
          key: "pid",
          width: 80,
        },
        {
          title: "用户名",
          slot: "name",
        },

        {
          title: "原图",
          slot: "image",
        },
        {
          title: "标题",
          key: "title",
        },
        {
          title: "上传时间",
          key: "time",
        },
        {
          title: "操作",
          slot: "action",
        },
      ],
      data: [],
      isflag: false,
      invincibleData: "",
      //   点击上传时发送的pid
      sendPid: "",
      users: "",
    };
  },
  mounted() {
    this.getAuditList();
  },

  methods: {
    async getAuditList() {
      const res = await get(`getAuditData.php?page=${this.currentPage}`);
      if (res) {
        this.data = res.waitList;
        this.allAuditNum = res.allAuditNum;
      }
    },
    pageChange(page) {
      this.currentPage = page;
      this.getAuditList();
    },
    //   不通过的方法
    unpass(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "<p>确认不通过？</p>",
        loading: true,
        onOk: async () => {
          const res = await get(`putAuditData.php?pid=${row.pid}`);
          if (res) {
            setTimeout(() => {
              this.$Modal.remove();
              this.$Message.info("审核完成");
            }, 1000);
            this.data = res.data;
          }
        },
      });
    },
    toViewImage(row) {
      this.$Notice.info({
        title: "操作提示",
        duration: 5,
        name: "viewImageNotice",
        render: (h) => {
          return h(
            "a",
            {
              class: "audit-notice",
            },
            [
              "1、单击图片可标注序号，生成序号图 ",
              h("a", "2、拖动标注序号以改变位置"),
              " ",
            ]
          );
        },
      });
      this.imageViewModal = !this.imageViewModal;
      this.imageViewSrc = row.image;
      this.sendPid = row.pid;
      const auditImage = document.getElementById("auditImage");
      this.imageViewModalLayout.width = auditImage.naturalWidth + 40;
      this.imageViewModalLayout.height = auditImage.naturalHeight;
      // 新增水印
      const text = document.createElement("span");
      text.className = "audit-addinfo";
      text.innerHTML = `@ ${this.users.name}`;
      auditImg.appendChild(text);
    },
    addPoint(e) {
      const auditImg = document.getElementById("auditImg");
      const span = document.createElement("span");
      span.className = "point";
      span.setAttribute("id", `drag-${this.count}`);
      //   拖动中禁止向html添加span
      if (!this.isflag) {
        this.count++;
        auditImg.appendChild(span);
      } else {
        this.isflag = false;
      }

      drag(span);

      span.style.top = e.offsetY + "px";
      span.style.left = e.offsetX + "px";
      span.innerHTML = this.count;
      span.addEventListener("mousedown", this.touchmoveHandle, false);
    },

    touchmoveHandle(e) {
      this.isflag = true;
    },
    // 将base64转成文件
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime,
      });
    },
    ischange(flag) {
      if (!flag) {
        this.cancel();
      }
    },
    cancel() {
      this.$Notice.close("viewImageNotice");
      this.count = 0;
      this.htmlUrl = "";
      const auditImg = document.getElementById("auditImg");
      const span = auditImg.querySelectorAll(".point");
      for (var i = 0; i < span.length; i++) {
        span[i].parentNode.removeChild(span[i]);
      }
    },
    view() {
      const auditImg = document.getElementById("auditImg");
      let vm = this;

      html2canvas(auditImg, {
        useCORS: true,
      }).then((canvas) => {
        let url = canvas.toDataURL("image/png");
        this.htmlUrl = url;
      });
    },
    // 如果通过
    pass() {
      const auditImg = document.getElementById("auditImg");
      html2canvas(auditImg, {
        useCORS: true,
      }).then((canvas) => {
        let url = canvas.toDataURL("image/png");

        let pageBlob = this.dataURLtoFile(url);
        this.sendUrl(pageBlob, this.count);
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        // this.sendUrl();
      });
    },
    // 图片上传服务器
    async sendUrl(file, count) {
      if (count === 0) return;
      //步骤1:将base64位图片转为formData上传格式
      let params = new FormData();
      let fileOfBlob = new File([file], new Date().getTime() + ".jpg");
      params.append("file", fileOfBlob);
      params.append("allOrderNum", count);
      params.append("pid", this.sendPid);
      params.append("userId", this.users.userId);
      console.log(params);
      const res = await upload("auditUpload.php", params);
      if (res) {
        if (res.status) {
          this.$Message.success(res.status);
          this.data = res.waitList;
          setTimeout(() => {
            this.imageViewModal = false;
          }, 1000);
          this.getAuditList();
        }
      }
    },

    setPoint(x, y, num) {
      // 获取到屏幕倒是是几倍屏。
      const myCanvas = document.getElementById("myCanvas");
      let ctx = myCanvas.getContext("2d");
      let getPixelRatio = function (context) {
        var backingStore =
          context.backingStorePixelRatio ||
          context.webkitBackingStorePixelRatio ||
          context.mozBackingStorePixelRatio ||
          context.msBackingStorePixelRatio ||
          context.oBackingStorePixelRatio ||
          context.backingStorePixelRatio ||
          1;
        return (window.devicePixelRatio || 1) / backingStore;
      };
      // iphone6下得到是2
      const pixelRatio = getPixelRatio(myCanvas);
      // 设置canvas的真实宽高
      myCanvas.width = pixelRatio * myCanvas.offsetWidth; // 想当于 2 * 375 = 750
      myCanvas.height = pixelRatio * myCanvas.offsetHeight;
    },
  },
};
</script>

<style>
ul,
li {
  list-style: none;
}

img {
  width: 100%;
}

.audit-image-box {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  margin: 10px 0;
  overflow: hidden;
}

.audit-image {
  width: 100%;
}

.modal-image-box {
  display: flex;
  position: relative;
  align-items: center;
  justify-content: space-between;
}

#auditImg {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.lispoint {
  background-color: red;
  line-height: 25px;
  font-weight: bold;
  text-align: center;
  color: white;
  width: 25px;
  height: 25px;
  border-radius: 100%;
}

.point {
  background-color: red;
  color: white;
  width: 25px;
  height: 25px;
  border-radius: 100%;
  position: absolute;
  text-align: center;
  line-height: 25px;
  font-weight: bold;
  cursor: move;
}

.audit-addinfo {
  position: absolute;
  right: 50px;
  bottom: 20px;
  color: white;
  text-shadow: 1px 1px 1px #000;
}

.auditPointList {
  position: absolute;
  top: 0;
  right: 10px;
  bottom: 0;
  background-color: rgba(64, 64, 64, 0.762);
  width: 100px;
  height: calc(100% - 5px);
  overflow-y: scroll;
  overflow-x: hidden;
}

.pointItem {
  color: white;
  padding: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  justify-content: space-between;
}

.pointItem:hover {
  background-color: rgb(180, 180, 180);
}

.audit-notice {
  height: 50px;
  line-height: 28px;
}
</style>
